package tictactoe;

import tictactoe.protocol.Protocol;

import java.io.IOException;
import java.util.Random;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * Created by IntelliJ IDEA.
 * User: Double
 * Date: 15.01.12
 * Time: 22:23
 * To change this template use File | Settings | File Templates.
 */
public class Game implements Runnable{

	int[] field = {3,5,7,9,4,3,7,9,6};
	private boolean flag = true;
	Client fclient;
	Client sclient;
	private int turn;   //0 - first, 1 - second
	private int victoryState;  //1 - first 2 -second
	public Game(Client fclient, Client sclient)
	{
		this.fclient = fclient;
		this.sclient = sclient;
		System.out.println("F:"+fclient.getName() + " S:" + sclient.getName());

		System.out.println("Game Field created");
		Logger.getLogger("TicTacToeServer").log(Level.ALL,"Game Field created. Players: "+fclient.getName()+","+sclient.getName());
		try
		{
			init();
		} catch (IOException e)
		{
			e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
		}


	}
	public boolean checkClients()
	{
		System.out.println("checkClients()");
		boolean ret = false;
		try {

			if(!isVictory()){
				if(fclient.hasMessage())
				{
					ret = true;
					System.out.println("First client has message");
					Protocol.decodeGamePacket(fclient.getMessage(),fclient,this);
				}
				else if(sclient.hasMessage())
				{
					ret = true;
					System.out.println("Second client has message");
					Protocol.decodeGamePacket(sclient.getMessage(),sclient,this);
				}
			}else{
				ret = false;
				System.out.println("Game Over!");
				Server.getClientProcessor().returnClient(fclient);
				Server.getClientProcessor().returnClient(sclient);
				Logger.getLogger("TicTacToeServer").log(Level.ALL,"Game Over for players: "+fclient.getName()+","+sclient.getName());
			}
		} catch (IOException e) {
			e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
		}



		return ret;
	}
	private void init() throws IOException
	{
		Random rand = new Random(System.currentTimeMillis());
		fclient.setFigure(rand.nextInt(2));
		if(fclient.getFigure()==1){
			sclient.setFigure(0);
		}else{
			sclient.setFigure(1);
		}
		System.out.println("F_figure:"+fclient.getFigure()+" S_figure:"+sclient.getFigure());
		if(rand.nextInt(2)==0)
		{
			System.out.println("Первым ходит первый игрок");
			if(fclient.getFigure()==1){
				//2
				turn=0;
				fclient.setTurnFlag(true);

				fclient.sendMsg(Protocol.encode(Protocol.start,"2"));
				sclient.sendMsg(Protocol.encode(Protocol.start, "1"));
			}else
			{
				//3
				turn=0;
				fclient.setTurnFlag(true);

				fclient.sendMsg(Protocol.encode(Protocol.start,"3"));
				sclient.sendMsg(Protocol.encode(Protocol.start, "0"));
			}
		}else
		{
			System.out.println("Первым ходит второй игрок");
			if(sclient.getFigure()==1){
				//0
				turn = 1;
				sclient.setTurnFlag(true);
				fclient.sendMsg(Protocol.encode(Protocol.start, "0"));
				sclient.sendMsg(Protocol.encode(Protocol.start, "3"));
			}else{
				//1
				turn = 1;
				sclient.setTurnFlag(true);
				fclient.sendMsg(Protocol.encode(Protocol.start, "1"));
				sclient.sendMsg(Protocol.encode(Protocol.start, "2"));
			}
		}

	}
	private void changeTurnFlag(){
		if(fclient.isTurnFlag()){
			fclient.setTurnFlag(false);
			sclient.setTurnFlag(true);
			System.out.println("Очередь пользователя - "+sclient.getName());

		}else{
			System.out.println("Очередь пользователя - "+fclient.getName());
			fclient.setTurnFlag(true);
			sclient.setTurnFlag(false);
		}
	}
	public synchronized boolean  makeStep(int pos,int figure) throws IOException {

		System.out.println("makestep()");
		if(field[pos]!=0 && field[pos]!=1){
			//System.out.println("Мы здесь");
			field[pos]=figure;
			fclient.sendMsg(Protocol.encode(Protocol.run, String.valueOf(pos)));
			sclient.sendMsg(Protocol.encode(Protocol.run, String.valueOf(pos)));
			changeTurnFlag();
			return true;
		}
		return false;

	}
	@Override
	public void run() {
		try {
			while(!isVictory()){
				if(fclient.hasMessage())
				{
					System.out.println("First client has message");
					Protocol.decodeGamePacket(fclient.getMessage(),fclient,this);
				}
				else if(sclient.hasMessage())
				{
					System.out.println("Second client has message");
					Protocol.decodeGamePacket(sclient.getMessage(),sclient,this);
				}


				if(isVictory())
				{
					System.out.println("Game Over!");
					if(victoryState==1)
					{
						sclient.sendMsg(Protocol.encode(Protocol.status, "lose"));
						fclient.sendMsg(Protocol.encode(Protocol.status, "win"));
					}else if(victoryState==2)
					{
						sclient.sendMsg(Protocol.encode(Protocol.status, "win"));
						fclient.sendMsg(Protocol.encode(Protocol.status, "lose"));
					}

					fclient.setPlaying(false);
					sclient.setPlaying(false);
					Server.getClientProcessor().returnClient(fclient);
					Server.getClientProcessor().returnClient(sclient);
					Logger.getLogger("TicTacToeServer").log(Level.ALL,"Game Over for players: "+fclient.getName()+","+sclient.getName());

					break;

				}

			}
		} catch (IOException e) {
			e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
		}


	}
	public boolean isVictory() throws IOException {
		boolean ret = false;

		if (    fclient.getFigure() == field[0] && field[0] == field[1] && field[1] == field[2] ||
				fclient.getFigure() == field[0] && field[3] == field[4] && field[4] == field[5] ||
				fclient.getFigure() == field[0] && field[6] == field[7] && field[7] == field[8] ||
				fclient.getFigure() == field[0] && field[0] == field[3] && field[3] == field[6] ||
				fclient.getFigure() == field[0] && field[1] == field[4] && field[4] == field[7] ||
				fclient.getFigure() == field[0] && field[2] == field[5] && field[5] == field[8] ||
				fclient.getFigure() == field[0] && field[0] == field[4] && field[4] == field[8] ||
				fclient.getFigure() == field[0] && field[2] == field[4] && field[4] == field[6])
		{

			victoryState = 1;

			ret = true;

		}
		else if(sclient.getFigure() == field[0] && field[0] == field[1] && field[1] == field[2] ||
				sclient.getFigure() == field[0] && field[3] == field[4] && field[4] == field[5] ||
				sclient.getFigure() == field[0] && field[6] == field[7] && field[7] == field[8] ||
				sclient.getFigure() == field[0] && field[0] == field[3] && field[3] == field[6] ||
				sclient.getFigure() == field[0] && field[1] == field[4] && field[4] == field[7] ||
				sclient.getFigure() == field[0] && field[2] == field[5] && field[5] == field[8] ||
				sclient.getFigure() == field[0] && field[0] == field[4] && field[4] == field[8] ||
				sclient.getFigure() == field[0] && field[2] == field[4] && field[4] == field[6]
				)
		{
			victoryState = 2;

			ret = true;
		}
		else{
			ret = false;
		}
		return ret;

	}
	void setField(){
		field = new int[]{1, 1, 1, 1, 1, 1, 1, 1, 1};
	}
}
